<?php namespace App\Services;

use Response, Request, Log, Session;
class Res{
	protected $formats = ['json', 'xml'];

	protected $openLog = true;

	/**
	 * Return success data info with assigned format.
	 *
	 * @param  array $data  General return data.
	 * @param  array $opt
	 *
	 * @return mixed Formated error info.
	 */
	public function success($data = array() , $opt = null) {
		$format = $this->_getFormat();
		if ($format === 'json') {
			$info = [
				'success' => 'true',
				'data' => $data
			];
			if ($opt != null && is_array($opt)) {
				$info += $opt;
			}
			return response()->json($info, 200);
		}
	}

	/**
	 * Return error info with assigned format.
	 *
	 * @param  string $message  General error message string.
	 * @param  mixed  $detail   Detail error message info, string or array
	 *
	 * @return mixed Formated error info.
	 */
	public function fail($message = '', $detail = null) {
		$format = $this->_getFormat();
		if ($format === 'json') {
			$info = [
				'success' => 'false',
				'error' => trans('errors.' . $message)
			];
			//if (env('APP_DEBUG')) {
//                        var_dump($detail);exit;
                        if($detail){
                            if (is_object($detail)) {
                                $info['details'] = $detail->first();
                            }else{
                                $info['details'] = trans('errors.' . $detail);
                            }
                        }else{
                            $info['details'] = '';
                        }
			//}
			// if($this->$openLog){
			// 	Log::info(var_export($info, true));
			// }
			return response()->json($info, 200);
		}
	}
        
        public function showMessage($type = 'error', $message = '', $url = 'index/index') {
            $result['type'] = $type;
            if ($message) {
                if (is_object($message)) {
                    $result['message'] = $message->first();
                } else {
                    $result['message'] = $message;     
                }
            } else {
                $result['message'] = '';     
            }
        
            $result['url'] = $url;
            return view('admin.message')->with('result', $result);
	}

	protected function _getFormat(){
		$format = strtolower(Request::get('format'));
		return $format = $format && in_array($format, $this->$formats) ? $format : 'json';
	}
}